/**
 * 省市县用js
 * 
 * @author 李伟
 */
$.namespace("common.area");

/**
 * 画面初始化处理
 */
common.area.init = function(opt) {
	common.area.initProvince(opt);
};
common.area.setArea= function(code){
	var province=code.substring(0,2)+"0000";
	$('#province').combobox('select', province);
	if(code.substring(2) == "0000"){
		return;
	}else{
		var city=code.substring(0,4)+"00";
		$('#city').combobox('select',city );
		if (code.substring(4) == "00") {
			return;
		} else {
			$('#county').combobox('select',code );
		}
	}
	
};
//加载隐藏域
common.area.loadHidden=function(){
	var str=$('#county').combobox('getValue');
	var provinceName=$('#province').combobox('getText');
	var cityName=$('#city').combobox('getText');
	var countyName=$('#county').combobox('getText');
    $("#areaCode").val(str); 
    $("#areaDesc").val(provinceName+cityName+countyName);
};
//港澳台加载隐藏域
common.area.loadHiddenForProvince=function(){
	var str=$('#province').combobox('getValue');
	var provinceName=$('#province').combobox('getText');
	$("#areaCode").val(str); 
	$("#areaDesc").val(provinceName);
};
/**
 * 初始化下拉框
 */
common.area.initProvince = function(opt){
    var opt=opt || {};
	 $("#area").append('<input id="province"    name="province" value="'+common.area.pleaseChoose+'" /> '
	            + '     <input id="city"  name="city" value="'+common.area.pleaseChoose+'" />  '
	            + '      <input id="county"  name="county" value="'+common.area.pleaseChoose+'" />  '
	            + '      <input id="areaDesc"  name="areaDesc" type="hidden"/>  '
	            + '         <input id="areaCode" name="areaCode" type="hidden" />  ');
	// 下拉框选择控件，下拉框的内容是动态查询数据库信息
    $('#province').combobox({
    	url : $.ctx + "/school/schoolinfo/getArea",    
                editable:false, //不可编辑状态
                cache: false,
                valueField:'admareaCode',  
                textField:'admareaName',
                width:180,
                panelHeight: 180,
                
                onChange: function(){
        	    	$("#city").combobox("enable");
                	 $("#city").combobox("setValue",common.area.pleaseChoose);
                	    $("#county").combobox("disable");
                	    $("#county").combobox("setValue",common.area.pleaseChoose);
//                	    $("#cregicounty").val('');
                	    var province = $('#province').combobox('getValue');    
                	    if(province==710000||province==810000||province==820000){//港澳台地区处理
                	    	$("#city").combobox("disable");
                	    	//延时500毫秒加载隐藏域，解决IE8反应慢的问题
                        	setTimeout("common.area.loadHiddenForProvince()",500);
                	    }else if(province!=common.area.pleaseChoos){
                	    $.ajax({
                	        type: "POST",
                	        url:  $.ctx + "/school/schoolinfo/getArea?admareaCode="+province,
                	        cache: false,
                			async : false,
                	        dataType : "json",
                	        success: function(data){
                	        $("#city").combobox("loadData",data);
                	                               }
                	                           }); 
                	                   }
                	    
                },onSelect: function(){
                	if(null!=opt.onProvinceChanged){
            	    	var text=$("#province").combobox("getText");
            	        opt.onProvinceChanged.apply(this,[province,text]);
            	    }
                }
                 });

    $('#city').combobox({
 
        editable:false, //不可编辑状态
        cache: false,
        disabled:true,//禁用组件
        valueField:'admareaCode',  
        textField:'admareaName',
        width:180,
        panelHeight: 180,


        onChange: function(){
//            $("#cregicounty").val('');
            $("#county").combobox("setValue",common.area.pleaseChoose);
            $("#county").combobox("enable");
            
            var city = $('#city').combobox('getValue');    
            if(city!=common.area.pleaseChoose){
                $.ajax({
                    type: "POST",
                    url: $.ctx + "/school/schoolinfo/getArea?admareaCode="+city,
                    cache: false,
            		async : false,
                    dataType : "json",
                    success: function(data){
                    $("#county").combobox("loadData",data);
                                           }
                }); 
             }
            
         },onSelect: function(){
        	 if(null!=opt.onCityChanged){
     	    	var text=$("#city").combobox("getText");
                 opt.onCityChanged.apply(this,[city,text]);
             }
        }
       }); 
    $('#county').combobox({
        editable:false, //不可编辑状态
        cache: false,
        disabled:true,//禁用组件
        valueField:'admareaCode',  
        textField:'admareaName',
        width:180,
        panelHeight: 180,
  
        
        onSelect: function(){
        	//延时500毫秒加载隐藏域，解决IE8反应慢的问题
        	setTimeout("common.area.loadHidden()",500);
        	if(null!=opt.onCountyChanged){
    	    	var text=$("#county").combobox("getText");
                opt.onCountyChanged.apply(this,[$('#county').val(),text]);
            }
       }
     }); 
   

};

$.fn.school = function(opts, paras) {
	if (typeof opts == "string") {
		return $.fn.school.methods[opts]($(this), paras);
	} else {
		opts = opts || {};
		opts.comboWidth = opts.comboWidth || 180;
		common.area.initSchool(opts, $(this));
	}
};

common.area.initSchool = function(opts, me) {
	me.empty();
	
	var schoolCombo = $("<input />").prependTo(me).combobox({
		editable : false,
		disabled : true,
		width : opts.comboWidth,
		panelHeight : 180,
		onBeforeLoad : function(param) {
			var def = $.Deferred();
			$(this).data("loadDef", def);
		},
		onLoadSuccess : function() {
			if ($(this).data("loadDef")) {
				$(this).data("loadDef").resolve();
			}
		},
		loadFilter : function(data) {
			if (opts.withBlank == true) {
				return [{'value' : '',
					'text' : opts.blankTxt || common.common.all,
					'selected' : true
				}].concat(data);
			} else {
				return data;
			}
		}
	});
	
	
	var countyCombo = $("<input />").prependTo(me).combobox({
		editable : false,
		disabled : true,
		width : opts.comboWidth,
		panelHeight : 180,
		onBeforeLoad : function(param) {
			var def = $.Deferred();
			$(this).data("loadDef", def);
		},
		onLoadSuccess : function() {
			if ($(this).data("loadDef")) {
				$(this).data("loadDef").resolve();
			}
		},
		onChange : function(newValue, oldValue) {
			if (isEmpty(newValue)) {
				schoolCombo.combobox('reload', $.ctx + '/common/area/getSchool?areaCode=' + cityCombo.combobox('getValue')).combobox('clear').combobox('enable');
			} else {
				schoolCombo.combobox('reload', $.ctx + '/common/area/getSchool?areaCode=' + newValue).combobox('clear').combobox('enable');
			}
		},
		loadFilter : function(data) {
			if (opts.withBlank == true) {
				return [{'value' : '',
					'text' : opts.blankTxt || common.common.all,
					'selected' : true
				}].concat(data);
			} else {
				return data;
			}
		}
	});
	
	var cityCombo = $("<input />").prependTo(me).combobox({
		editable : false,
		disabled : true,
		width : opts.comboWidth,
		panelHeight : 180,
		onBeforeLoad : function(param) {
			var def = $.Deferred();
			$(this).data("loadDef", def);
		},
		onLoadSuccess : function() {
			if ($(this).data("loadDef")) {
				$(this).data("loadDef").resolve();
			}
		},
		onChange : function(newValue, oldValue) {
			if (isEmpty(newValue)) {
				countyCombo.combobox('reset').combobox('disable');
				schoolCombo.combobox('reset').combobox('disable');
			} else {
				countyCombo.combobox('reload', $.ctx + '/common/area/getSchoolCounty?cityCode=' + newValue).combobox('clear').combobox('enable');
				schoolCombo.combobox('reload', $.ctx + '/common/area/getSchool?areaCode=' + newValue).combobox('clear').combobox('enable');
			}
		},
		loadFilter : function(data) {
			if (opts.withBlank == true) {
				return [{'value' : '',
					'text' : opts.blankTxt || common.common.all,
					'selected' : true
				}].concat(data);
			} else {
				return data;
			}
		}
	});
	
	var provinceCombo = $("<input />").prependTo(me).combobox({
		url : $.ctx + '/common/area/getSchoolProvince',
		editable : false,
		width : opts.comboWidth,
		panelHeight : 180,
		onBeforeLoad : function(param) {
			var def = $.Deferred();
			$(this).data("loadDef", def);
		},
		onLoadSuccess : function() {
			if ($(this).data("loadDef")) {
				$(this).data("loadDef").resolve();
			}
		},
		onChange : function(newValue, oldValue) {
			if (isEmpty(newValue)) {
				cityCombo.combobox('reset').combobox('disable');
				countyCombo.combobox('reset').combobox('disable');
				schoolCombo.combobox('reset').combobox('disable');
			} else {
				cityCombo.combobox('reload', $.ctx + '/common/area/getSchoolCity?provinceCode=' + newValue).combobox('clear').combobox('enable');
				countyCombo.combobox('reset').combobox('disable');
				schoolCombo.combobox('reset').combobox('disable');
			}
		},
		loadFilter : function(data) {
			if (opts.withBlank == true) {
				return [{'value' : '',
					'text' : opts.blankTxt || common.common.all,
					'selected' : true
				}].concat(data);
			} else {
				return data;
			}
		}
	});
	
	if ($.fn.combobox.methods.getLoadDef == undefined) {
		$.fn.combobox.methods.getLoadDef = function(me) {
			var loadDef = me.data('loadDef');
			if(loadDef) {
				return loadDef.promise();
			} else {
				return null;
			}
		};
	}
	
	me.data('provinceCombo', provinceCombo);
	me.data('cityCombo', cityCombo);
	me.data('countyCombo', countyCombo);
	me.data('schoolCombo', schoolCombo);
	me.children(".combo").css('margin-right', '8px');
	
	me.school('setSchool', opts.schoolCode);
};

$.fn.school.methods = {
	getSchoolCode : function(me) {
		var schoolCombo = me.data('schoolCombo');
		return schoolCombo.combobox('getValue');
	},
	getSchoolName : function(me) {
		var schoolCombo = me.data('schoolCombo');
		if (isEmpty(schoolCombo.combobox('getValue'))) {
			return schoolCombo.combobox('getValue');
		} else {
			return schoolCombo.combobox('getText');
		}
	},
	setSchool : function(me, schoolCode) {
		var provinceCombo = me.data('provinceCombo');
		var cityCombo = me.data('cityCombo');
		var countyCombo = me.data('countyCombo');
		var schoolCombo = me.data('schoolCombo');
		$.get($.ctx + '/common/area/getSchoolArea?schoolCode=' + schoolCode, function(data) {
			provinceCombo.combobox('getLoadDef').done(function() {
				provinceCombo.combobox('setValue', data.areaCodeProvince || '');
				cityCombo.combobox('getLoadDef').done(function() {
					cityCombo.combobox('setValue', data.areaCodeCity || '');
					$.when(countyCombo.combobox('getLoadDef'), schoolCombo.combobox('getLoadDef')).done(function() {
						countyCombo.combobox('setValue', data.areaCodeCounty);
						schoolCombo.combobox('getLoadDef').done(function() {
							schoolCombo.combobox('setValue', data.schoolCode || '');
						});
					});
				});
			});
		});
	},
	reset : function(me) {
		var provinceCombo = me.data('provinceCombo');
		provinceCombo.combobox('reset');
	}
};

$.fn.area = function(opts, paras) {
	if (typeof opts == "string") {
		return $.fn.area.methods[opts]($(this), paras);
	} else {
		opts = opts || {};
		opts.comboWidth = opts.comboWidth || 180;
		common.area.initArea(opts, $(this));
	}
};

common.area.initArea = function(opts, me) {
	me.empty();
	
	var countyCombo = $("<input />").prependTo(me).combobox({
		editable : false,
		disabled : true,
		width : opts.comboWidth,
		panelHeight : 180,
		textField : 'admareaName',
		valueField : 'admareaId',
		onBeforeLoad : function(param) {
			var def = $.Deferred();
			$(this).data("loadDef", def);
		},
		onLoadSuccess : function() {
			if ($(this).data("loadDef")) {
				$(this).data("loadDef").resolve();
			}
		},
		loadFilter : function(data) {
			if (opts.withBlank == true) {
				return [{'admareaId' : '',
					'admareaName' : opts.blankTxt || common.common.all,
					'selected' : true
				}].concat(data);
			} else {
				return data;
			}
		}
	});	
	
	var cityCombo = $("<input />").prependTo(me).combobox({
		editable : false,
		disabled : true,
		width : opts.comboWidth,
		panelHeight : 180,
		textField : 'admareaName',
		valueField : 'admareaId',
		onBeforeLoad : function(param) {
			var def = $.Deferred();
			$(this).data("loadDef", def);
		},
		onLoadSuccess : function() {
			if ($(this).data("loadDef")) {
				$(this).data("loadDef").resolve();
			}
		},
		onChange : function(newValue, oldValue) {
			if (isEmpty(newValue)) {
				countyCombo.combobox('reset').combobox('disable');
			} else {
				countyCombo.combobox('reload', $.ctx + "/common/area/county?city=" + newValue).combobox('clear').combobox('enable');
			}
		},
		loadFilter : function(data) {
			if (opts.withBlank == true) {
				return [{'admareaId' : '',
					'admareaName' : opts.blankTxt || common.common.all,
					'selected' : true
				}].concat(data);
			} else {
				return data;
			}
		}
	});
	
	var provinceCombo = $("<input />").prependTo(me).combobox({
		url : $.ctx + '/common/area/province',
		editable : false,
		width : opts.comboWidth,
		panelHeight : 180,
		textField : 'admareaName',
		valueField : 'admareaId',
		onBeforeLoad : function(param) {
			var def = $.Deferred();
			$(this).data("loadDef", def);
		},
		onLoadSuccess : function() {
			if ($(this).data("loadDef")) {
				$(this).data("loadDef").resolve();
			}
		},
		onChange : function(newValue, oldValue) {
			if (isEmpty(newValue)) {
				cityCombo.combobox('reset').combobox('disable');
				countyCombo.combobox('reset').combobox('disable');
			} else {
				cityCombo.combobox('reload', $.ctx + "/common/area/city?province=" + newValue).combobox('clear').combobox('enable');
				countyCombo.combobox('reset').combobox('disable');
			}
		},
		loadFilter : function(data) {
			if (opts.withBlank == true) {
				return [{'admareaId' : '',
					'admareaName' : opts.blankTxt || common.common.all,
					'selected' : true
				}].concat(data);
			} else {
				return data;
			}
		}
	});
	
	if ($.fn.area.methods.getLoadDef == undefined) {
		$.fn.area.methods.getLoadDef = function(me) {
			var loadDef = me.data('loadDef');
			if(loadDef) {
				return loadDef.promise();
			} else {
				return null;
			}
		};
	}
	
	me.data('provinceCombo', provinceCombo);
	me.data('cityCombo', cityCombo);
	me.data('countyCombo', countyCombo);

	me.children(".combo:not(:last)").css('margin-right', '8px');
};

$.fn.area.methods = {
	getProvinceCode : function(me) {
		var provinceCombo = me.data('provinceCombo');
		return provinceCombo.combobox('getValue');
	},
	getProvinceName : function(me) {
		var provinceCombo = me.data('provinceCombo');
		if (isEmpty(provinceCombo.combobox('getValue'))) {
			return provinceCombo.combobox('getValue');
		} else {
			return provinceCombo.combobox('getText');
		}
	},
	getCityCode : function(me) {
		var cityCombo = me.data('cityCombo');
		return cityCombo.combobox('getValue');
	},
	getCityName : function(me) {
		var cityCombo = me.data('cityCombo');
		if (isEmpty(cityCombo.combobox('getValue'))) {
			return cityCombo.combobox('getValue');
		} else {
			return cityCombo.combobox('getText');
		}
	},
	getCountyCode : function(me) {
		var countyCombo = me.data('countyCombo');
		return countyCombo.combobox('getValue');
	},
	getCountyName : function(me) {
		var countyCombo = me.data('countyCombo');
		if (isEmpty(countyCombo.combobox('getValue'))) {
			return countyCombo.combobox('getValue');
		} else {
			return countyCombo.combobox('getText');
		}
	},
	getAreaCode : function(me) {
		return me.area('getCountyCode') || me.area('getCityCode') || me.area('getProvinceCode');
	},
	getAreaName : function(me) {
		return me.area('getCountyName') || me.area('getCityName') || me.area('getProvinceName');
	},
	setArea : function(me, areaCode) {
		var provinceCombo = me.data('provinceCombo');
		var cityCombo = me.data('cityCombo');
		var countyCombo = me.data('countyCombo');
		var getComboVal = function(n) {
			return n.value;
		};
		var provinceArr = $.map(provinceCombo.combobox('getData'), getComboVal);
		var cityArr = $.map(cityCombo.combobox('getData'), getComboVal);
		var countyArr = $.map(countyCombo.combobox('getData'), getComboVal);
		
		if ($.inArray(areaCode, countyArr) < 0) {
			if ($.inArray(areaCode, cityArr) < 0) {
				if ($.inArray(areaCode, provinceArr) >= 0) {
					provinceCombo.combobox('select', areaCode);
				}
			} else {
				cityCombo.combobox('select', areaCode);
				provinceCombo.combobox('select', areaCode.substr(0, 2) + '0000');
			}
		} else {
			countyCombo.combobox('select', areaCode);
			cityCombo.combobox('select', areaCode.substr(0, 4) + '00');
			provinceCombo.combobox('select', areaCode.substr(0, 2) + '0000');
		}
	},
	reset : function(me) {
		var provinceCombo = me.data('provinceCombo');
		provinceCombo.combobox('reset');
	}
};

function openAreaTreeWin(opts) {
	if ($("#areaTreeWin").length == 0) {
		liandisys.dialog.showWindowById({
			itemId : "areaTreeWin",
			href : $.ctx + "/common/area/areaTreeWin",
			width : 500,
			resizable : false,
			title :  '地区选择',
			onLoad : function() {
				common.subpage.areaTree.backFn = opts.backFn;
				common.subpage.areaTree.initCodes = isEmpty(opts.initCodes) ? "000000" : opts.initCodes;
				common.subpage.areaTree.areaLevel = opts.areaLevel;
				common.subpage.areaTree.checkedIds = opts.checkedIds;
				common.subpage.areaTree.singleSelect = opts.singleSelect;
				common.subpage.areaTree.deferred.resolve();
			}
		});
	} else {
		liandisys.dialog.showWindowByItem({
			item : $("#areaTreeWin"),
			href : $.ctx + "/common/area/areaTreeWin",
			width : 500,
			resizable : false,
			title :  '地区选择',
			onLoad : function() {
				common.subpage.areaTree.backFn = opts.backFn;
				common.subpage.areaTree.initCodes = isEmpty(opts.initCodes) ? "000000" : opts.initCodes;
				common.subpage.areaTree.areaLevel = opts.areaLevel;
				common.subpage.areaTree.checkedIds = opts.checkedIds;
				common.subpage.areaTree.singleSelect = opts.singleSelect;
				common.subpage.areaTree.deferred.resolve();
			}
		});
	}
}
